package org.dromara.frame.init;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 抽帧服务
 *
 * @author samuel
 * @date 2024-03-25 18:14:55
 */

@Component
public class LoadOpencv implements CommandLineRunner {

    @javax.annotation.Resource
    private ResourceLoader resourceLoader;

    @Override
    public void run(String... args) throws Exception {
        loadOpenCVLibrary();
    }

    private void loadOpenCVLibrary() throws IOException {
        // 将 OpenCV 库从 JAR 文件中提取到临时目录
        String fileName = "libopencv_java490";
        String fileSuffix = ".dylib";
        if (isLinux()) {
            fileName = "libopencv_java490";
            fileSuffix = ".so";
        }
        // 将 OpenCV 库从 JAR 文件中提取到临时目录
        Resource resource = resourceLoader.getResource("classpath:" + fileName + fileSuffix);
        InputStream inputStream = resource.getInputStream();
        File tempFile = File.createTempFile(fileName, fileSuffix);

        tempFile.deleteOnExit();
        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        // 加载提取出的 OpenCV 库
        System.load(tempFile.getAbsolutePath());
        System.out.println("OpenCV library loaded from: " + tempFile.getAbsolutePath());
    }

    private static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().startsWith("linux");
    }
}
